package com.lst.tools.basics.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
public class HiddenUtils {

    private static final String HIDE_SYMBOL = "*";
    private static final int HIDE_SYMBOL_LENGTH = 3;

    /**
     * 打***
     *
     * @param text        需要隐藏的字符串
     * @param startLength 保留前面多长字符
     * @return
     */
    public static String hidden(String text, int startLength) {
        if (StringUtils.isBlank(text)) {
            return text;
        }
        char[] chars = text.toCharArray();
        StringBuilder response = new StringBuilder();
        for (int i = 0; i < chars.length; ) {
            char aChar = chars[i];
            if (i < startLength) {
                response.append(aChar);
            } else {
                response.append(HIDE_SYMBOL);
            }
            i++;
        }
        return response.toString();
    }

    /**
     * 打***
     *
     * @param text        需要隐藏的字符串
     * @param startLength 保留前面多长字符
     * @param endLength   保留后面面多长字符
     * @return
     */
    public static String hidden(String text, int startLength, int endLength) {
        return hiddenByHideSymbolLength(text, HIDE_SYMBOL_LENGTH, startLength, endLength);
    }

    /**
     * 打***
     *
     * @param text        需要隐藏的字符串
     * @param startLength 保留前面多长字符
     * @param endLength   保留后面面多长字符
     * @return
     */
    public static String hiddenByHideSymbolLength(String text, int hideSymbolLength, int startLength, int endLength) {
        if (StringUtils.isBlank(text)) {
            return text;
        }
        char[] chars = text.toCharArray();
        StringBuilder response = new StringBuilder();
        int length = chars.length;
        int endIndex = length - endLength;
        int j = 0;
        for (int i = 0; i < length; ) {
            char aChar = chars[i];
            if (i < startLength || i >= endIndex) {
                response.append(aChar);
            } else {
                if (j < hideSymbolLength) {
                    response.append(HIDE_SYMBOL);
                }
                j++;
            }
            i++;
        }
        return response.toString();
    }
}
